package com.ft.javaio.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Iterator;

/**
 * @Author RenPu
 * @Date 2023/7/19 11:22
 * @Version 1.0
 * @Description:
 **/
public class NIOClient {

    private static CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
    private static CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();

    public static void main(String[] args) {

        for (int i = 0; i <10 ; i++) {

            new Work().start();

        }

    }

    static class Work extends Thread {

        SocketChannel channel=null;
        Selector selector=null;
        @Override


        /**
         * 初始化NIO客户端，SocketChannel,selector组件
         *  1：绑定服务端暴露的端口，以及ip
         *  2：设置为非阻塞
         *  3：注册复用组件以及声明监测事件
         *  4：
         */
   public void run() {
     try {
         channel = SocketChannel.open();
         channel.connect(new InetSocketAddress("localhost", 9000));
         channel.configureBlocking(false);
         selector = Selector.open();
         channel.register(selector, SelectionKey.OP_CONNECT);

         while (true){
             selector.select();
             Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
             while (iterator.hasNext()){
                 SelectionKey key = iterator.next();

                 iterator.remove();
                 if(key.isConnectable()){
                     if(channel.isConnectionPending()){
                         if(channel.finishConnect()){
                           key.interestOps(SelectionKey.OP_READ);
                           channel.write(encoder.encode(CharBuffer.wrap("你好")));
                         }else {
                             key.cancel();
                         }

                     }
                 }else if(key.isReadable()){

                     ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                     channel.read(byteBuffer);
                     byteBuffer.flip();
                     CharBuffer charBuffer = decoder.decode(byteBuffer);
                     String response = charBuffer.toString();
                     System.out.println("[" + Thread.currentThread().getName()
                             + "]收到响应：" + response);

                     channel.write(encoder.encode(CharBuffer.wrap("你好")));

                 }

             }

         }

     }catch (Throwable e){
         e.printStackTrace();
     } finally{
         if(channel != null){
             try {
                 channel.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }

         if(selector != null){
             try {
                 selector.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }
  }

    }

 }
